package com.example.tools.logging.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder;

import javax.servlet.http.HttpServletResponseWrapper;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author yang
 */
@Aspect
public class SysLogAspect {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut("@annotation(com.example.tools.logging.annotation.SysLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //通过uuid关联请求参数和返回参数
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        methodBefore(pjp, uuid);
        try {
            Object proceed = pjp.proceed();
            methodAfterReturing(proceed, uuid);
            return proceed;
        } catch (Exception e) {
            log.error("[{}]Response异常内容:{}", uuid, e);
            throw e;
        }


        // MethodSignature signature = (MethodSignature) pjp.getSignature();
        // Method method = signature.getMethod();
        // //类名
        // String className = pjp.getTarget().getClass().getName();
        // //方法名
        // String methodName = signature.getName();
        //
        // SysLog syslog = method.getAnnotation(SysLog.class);
        // //操作
        // String operator =syslog.value();
        //
        // long beginTime = System.currentTimeMillis();
        //
        // Object returnValue = null;
        // Exception ex = null;
        // try {
        //     returnValue = pjp.proceed();
        //     return returnValue;
        // } catch (Exception e) {
        //     ex = e;
        //     throw e;
        // } finally {
        //     long cost = System.currentTimeMillis() - beginTime;
        //     if (ex != null) {
        //         log.error("[class: {}][method: {}][operator: {}][cost: {}ms][args: {}][发生异常]",
        //                 className, methodName, operator, pjp.getArgs(), cost,ex);
        //     } else {
        //         log.info("[class: {}][method: {}][operator: {}][cost: {}ms][args: {}][return: {}]",
        //                 className, methodName, operator, cost, pjp.getArgs(), cost,returnValue);
        //     }
        // }

    }

    public void methodBefore(JoinPoint joinPoint, String uuid) {
        // 打印请求内容
        try {
            // 下面两个数组中，参数值和参数名的个数和位置是一一对应的。
            Object[] objs = joinPoint.getArgs();
            String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames(); // 参数名
            Map<String, Object> paramMap = new HashMap<String, Object>();
            for (int i = 0; i < objs.length; i++) {
                if (!(objs[i] instanceof ExtendedServletRequestDataBinder) && !(objs[i] instanceof HttpServletResponseWrapper)) {
                    paramMap.put(argNames[i], objs[i]);
                }
            }
            if (paramMap.size() > 0) {
                log.info("\n[{}]方法:{}\n参数:{}", uuid, joinPoint.getSignature(), JSONObject.toJSONString(paramMap));
            }
        } catch (Exception e) {
            log.error("[{}]AOP methodBefore:", uuid, e);
        }
    }

    public void methodAfterReturing(Object o, String uuid) {
        try {
             if (null != o) {
                log.info("[{}]Response内容:{}", uuid, JSONObject.toJSON(o));
              }
        } catch (Exception e) {
            log.error("[{}]AOP methodAfterReturing:", uuid, e);
        }
    }

}